import React, { useRef, useState, useEffect } from 'react';
import { Form, Input, Button, NavBar, TextArea, DatePicker, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import './style.css';

const ConsultationNew = () => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const canvasRef = useRef(null);
  const signatureImageRef = useRef(null);
  const [signatureData, setSignatureData] = useState('');
  
  const [isDrawing, setIsDrawing] = useState(false);
  const [lastPosition, setLastPosition] = useState({ x: 0, y: 0 });
  const [penColor, setPenColor] = useState('#000000');
  const [penSize, setPenSize] = useState(2);
   const [form] = Form.useForm(); // Use Form.useForm() instead of useState
 
  // 初始化画布
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    
    // 设置画布背景为白色
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 调整画布大小以匹配显示大小
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    
    ctx.scale(dpr, dpr);
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
  }, []);

  // 获取位置函数
  const getPosition = (e) => {
    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    
    let x, y;
    if (e.touches && e.touches[0]) {
      x = (e.touches[0].clientX - rect.left) * (canvas.width / rect.width / dpr);
      y = (e.touches[0].clientY - rect.top) * (canvas.height / rect.height / dpr);
    } else if (e.clientX && e.clientY) {
      x = (e.clientX - rect.left) * (canvas.width / rect.width / dpr);
      y = (e.clientY - rect.top) * (canvas.height / rect.height / dpr);
    }
    return { x, y };
  };

  // 开始绘制
  const startDrawing = (e) => {
    e.preventDefault();
    setIsDrawing(true);
    const position = getPosition(e);
    setLastPosition(position);
  };

  // 绘制过程
  const draw = (e) => {
    e.preventDefault();
    if (!isDrawing) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const position = getPosition(e);

    ctx.beginPath();
    ctx.moveTo(lastPosition.x, lastPosition.y);
    ctx.lineTo(position.x, position.y);
    ctx.strokeStyle = penColor;
    ctx.lineWidth = penSize;
    ctx.stroke();

    setLastPosition(position);
  };

  // 结束绘制
  const stopDrawing = () => {
    setIsDrawing(false);
  };

  // 清除画布
  const clearCanvas = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    setSignatureData('');
    if (signatureImageRef.current) {
      signatureImageRef.current.src = '';
    }
  };

  // 保存签名
  const saveSignature = () => {
    const canvas = canvasRef.current;
    if (isCanvasBlank(canvas)) {
      Toast.show({
        content: '请先签名！',
        position: 'center',
      });
      return;
    }
    const dataURL = canvas.toDataURL('image/png');
    setSignatureData(dataURL);
    if (signatureImageRef.current) {
      signatureImageRef.current.src = dataURL;
    }
    Toast.show({
      content: '签名已保存',
      position: 'center',
    });
  };

  // 下载签名
  const downloadSignature = () => {
    if (!signatureData) {
      Toast.show({
        content: '请先保存签名！',
        position: 'center',
      });
      return;
    }
    const link = document.createElement('a');
    link.download = 'signature.png';
    link.href = signatureData;
    link.click();
  };

  // 检查画布是否为空
  const isCanvasBlank = (canvas) => {
    const ctx = canvas.getContext('2d');
    const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
    return !pixels.some(pixel => pixel !== 255);
  };

  // 表单提交
  const onFinish = async (values) => {
    try {
      if (!signatureData) {
        Toast.show({
          content: '请先保存签名！',
          position: 'center',
        });
        return;
      }
      const response = await axios.post(
        "http://localhost:3000/zhuan/zhuanadd",
        values
      );
      
      if (response.data.code === 200) {
        Toast.show({
          content: '提交成功',
          position: 'center',
        });
        navigate('/layout/referral');
      } else {
        Toast.show({
          content: response.data.msg || '提交失败',
          position: 'center',
        });
      }
    } catch (error) {
      console.error("提交失败:", error);
      Toast.show({
        content: '提交失败，请重试',
        position: 'center',
      });
    }
  };

  return (
    <div className="consultation-new">
      <NavBar onBack={() => navigate(-1)}>新建转诊</NavBar>
      <Form
        form={form}
        onFinish={onFinish}
        layout="vertical"
      >
        <Form.Item
          name="huanName"
          label="患者姓名"
          rules={[{ required: true, message: '请输入患者姓名' }]}
        >
          <Input placeholder="请输入患者姓名" />
        </Form.Item>

        <Form.Item 
          name="age" 
          label="年龄" 
          rules={[{ required: true, message: '请输入年龄' }]}
        >
          <Input type="number" placeholder="请输入年龄" />
        </Form.Item>

        <Form.Item 
          name="toDepartment" 
          label="转科室" 
          rules={[{ required: true, message: '请选择科室' }]}
        >
          <Input placeholder="需要去的科室" />
        </Form.Item>
        <Form.Item 
          name="fromDepartment" 
          label="科室" 
          rules={[{ required: true, message: '请选择科室' }]}
        >
          <Input placeholder="请选择科室" />
        </Form.Item>
        <Form.Item
          name="desc"
          label="病情描述"
          rules={[{ required: true, message: '请详细描述患者病情' }]}
        >
          <TextArea placeholder="请详细描述患者病情" rows={4} />
        </Form.Item>

        <Form.Item
          name="expectedTime"
          label="期望会诊时间"
          rules={[{ required: true, message: "请选择期望会诊时间" }]}
          trigger="onConfirm"
          onClick={() => setVisible(true)}
        >
          <DatePicker
            visible={visible}
            onClose={() => setVisible(false)}
            onConfirm={(val) => {
              form.setFieldValue('expectedTime', val);
              setVisible(false);
            }}
            precision="day"
            min={new Date()}
          >
            {(value) => value ? value.toLocaleDateString() : "请选择日期"}
          </DatePicker>
        </Form.Item>

        <div className="signature-section">
          <h3>签名区域</h3>
          <div className="signature-container">
            <div className="canvas-container">
              <canvas
                ref={canvasRef}
                style={{
                  width: '100%',
                  height: '250px',
                  border: '1px solid #ccc',
                  background: '#fff',
                  borderRadius: '4px',
                  touchAction: 'none'
                }}
                onTouchStart={startDrawing}
                onTouchMove={draw}
                onTouchEnd={stopDrawing}
                onTouchCancel={stopDrawing}
                onMouseDown={startDrawing}
                onMouseMove={draw}
                onMouseUp={stopDrawing}
                onMouseLeave={stopDrawing}
              />
            </div>

            <div className="controls">
              <div className="control-group">
                <span>笔触颜色：</span>
                <input
                  type="color"
                  value={penColor}
                  onChange={(e) => setPenColor(e.target.value)}
                  style={{ width: '50px', height: '30px' }}
                />
              </div>

              <div className="control-group">
                <span>笔触大小：</span>
                <input
                  type="range"
                  min="1"
                  max="20"
                  value={penSize}
                  onChange={(e) => setPenSize(parseInt(e.target.value))}
                  style={{ width: '100px' }}
                />
                <span>{penSize}px</span>
              </div>

              <div className="button-group">
                <Button onClick={clearCanvas}>清除</Button>
                <Button color="primary" onClick={saveSignature}>保存</Button>
                <Button onClick={downloadSignature}>下载</Button>
              </div>
            </div>

            <div className="signature-preview">
              <h4>签名预览：</h4>
              <div className="preview-box">
                <img
                  ref={signatureImageRef}
                  alt=""
                  style={{
                    maxWidth: '100%',
                    maxHeight: '150px',
                    border: '1px dashed #ccc',
                    borderRadius: '4px',
                    display: 'block',
                    margin: '8px 0'
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: '16px' }}>
          <Button 
            block 
            type="submit" 
            color="primary"
          >
            提交申请
          </Button>
        </div>
      </Form>
    </div>
  );
};

export default ConsultationNew;